package com.qijian.common.utils.easyexcel.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gw
 */
public class CustomSheetWriteHandler implements SheetWriteHandler {

    private Map<Integer, Map<Integer, Object>> fillData;

    private Boolean isHide = false;

    public CustomSheetWriteHandler() {
    }

    public CustomSheetWriteHandler(Boolean isHide) {
        this.isHide = isHide;
    }

    public CustomSheetWriteHandler fill(Integer row, Integer column, Object data) {
        if (fillData == null) {
            fillData = new HashMap<>(16);
        }
        fillData.computeIfAbsent(row, k -> new HashMap<>(16)).put(column, data);
        return this;
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        fillData.forEach((r, cd) -> {
            Sheet sheet = writeSheetHolder.getSheet();
            Row row = sheet.getRow(r);
            if (row == null) {
                row = sheet.createRow(r);
            }
            Row finalRow = row;
            cd.forEach((c, d) -> {
                Cell cell = finalRow.getCell(c);
                if (cell == null) {
                    cell = finalRow.createCell(c);
                }
                cell.setCellValue(String.valueOf(d));
            });
            if (isHide) {
                if (row.getHeightInPoints() != 0) {
                    row.setHeightInPoints(0);
                }
            }
        });


    }
}
